<?php

class CommentController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',
				'actions'=>array('index'),
				'users'=>array('*'),
			),
			array('allow',
				'actions'=>array('create','update','delete','rate','report','getQuote'),
				'users'=>array('@'),
			),
			array('deny', // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Default action.
	 * @throws CHttpException when called
	 */
	public function actionIndex()
	{
		throw new CHttpException(404,Yii::t('frontend','The page your requested could not be found.'));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model = $this->loadModel($id);
		$entry = Entry::model()->findByPk($model->entryId);

		$this->performAjaxValidation($model);

		if (isset($_POST['Comment']))
		{
			$model->attributes = $_POST['Comment'];
			$model->body = Yii::app()->bbcodeParser->bbcode2html($model->body);
			$model->edited = 1; // comment is now edited
			
			if ($model->save())
			{
				Yii::app()->user->setFlash(WebUser::FLASH_SUCCESS,Yii::t('flash','Comment updated.'));
				$this->redirect(array('entry/view','id'=>$model->entryId,'#'=>'comment-'.$model->id)); // TODO: Fix the issue causing the page to jump when specifying a hash.
			}
		}

		$model->body = Yii::app()->bbcodeParser->html2bbcode($model->body);

		$this->render('update',array(
			'model'=>$model,
			'entry'=>$entry,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$model = $this->loadModel($id);

		if ($model->creatorId === Yii::app()->user->id || Yii::app()->user->isAdmin)
		{
			Yii::app()->user->setFlash(WebUser::FLASH_SUCCESS,Yii::t('flash','Comment deleted.'));
			$model->delete();
			$this->redirect(array('entry/view','id'=>$model->entryId,'#'=>'comments'));
		}
		else
			throw new CHttpException(404,Yii::t('frontend','Access denied.'));
	}

	/**
	 * Rates a particular model.
	 * @param $id the ID of the model to be rated
	 */
	public function actionRate($id)
	{
		$type = isset($_POST['type']) ? $_POST['type'] : null;
		$validTypes = Rate::getValidTypes();

		if (Yii::app()->request->isPostRequest && $type !== null && in_array($type, $validTypes))
		{
			$model = $this->loadModel($id);
			$model->rate(Yii::app()->user->id, $type);
			echo $this->renderPartial('_rate',array('model'=>$model));
			Yii::app()->end();
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Reports a particular model to the administration by sending an email.
	 * @param $id the ID of the model to be reported
	 */
	public function actionReport($id)
	{
		$model = $this->loadModel($id);

		/** @var User $user */
		$user = Yii::app()->user->loadModel();

		/** @var PHPMailer $mailer */
		$mailer = Yii::app()->mailer;
		$mailer->CharSet = Yii::app()->charset;
		$mailer->From = Yii::app()->params['systemEmail'];
		$mailer->FromName = 'Kuvakilpailut.net';
		$mailer->AddAddress(Yii::app()->params['contactEmail']);
		$mailer->Subject = Yii::t('email','Inappropriate comment');
		$mailer->getView('_reportComment',array('model'=>$model,'user'=>$user));
		$mailer->isHTML(true);
		$mailer->Send();

		Yii::app()->user->setFlash(WebUser::FLASH_NOTICE,Yii::t('flash','Comment reported.'));
		$this->redirect(array('entry/view','id'=>$model->entryId,'#'=>'comment-'.$model->id));
	}

	/**
	 * Returns the quotation of a particular model.
	 * @param $id the ID of the model to be quoted
	 * @return string the quote.
	 */
	public function actionGetQuote($id)
	{
		$model = $this->loadModel($id);
		$body = Yii::app()->bbcodeParser->html2bbcode($model->body);
		$body = preg_replace('/\[quote(?:\=?)(.*?)\](.*?)\[\/quote\]/i', '', $body);
		echo $model !== null ? '[quote='.$model->alias.']'.$body.'[/quote]'.PHP_EOL.PHP_EOL : '';
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Comment the model
	 */
	public function loadModel($id)
	{
		$model=Comment::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
